<template>
    <v-card class="mx-auto" style="height:94vh">

        <v-card>
            <div style="display:flex; align-items:center; padding:5px 0 5px 12px;">
                <h3 @click="loadMatrixData()" style="margin:0; padding:0; white-space:nowrap;">缺陷分类矩阵图</h3>
                <div style="margin-left:30px;">
                    <v-select
                            v-model="selectedProblemClass"
                            :items="problemClassList"
                            item-text="label"
                            item-value="value"
                            label="问题大类"
                            style="width:120px;"
                            dense
                            outlined
                            hide-details
                            @change="onProblemClassChange"
                    ></v-select>
                </div>
            </div>
            <div ref="matrixTarget" style="width:100%;height:45vh"></div>
        </v-card>

        <v-card style="padding-left:10px;padding-right:10px;margin-top:3px;padding-bottom:20px">
            <h3 style="padding-top:3px" >【{{problem_subclass}}】再发防止思维导图</h3>
            <div style="position:relative;padding:20px;">
                <!-- SVG画布用于绘制连接线 -->
                <svg ref="mindmapSvg" style="position:absolute;top:0;left:0;width:100%;height:100%;pointer-events:none;z-index:1">
                    <path v-for="(line, index) in connectionLines" :key="index"
                          :d="line.path"
                          :stroke="line.color" 
                          stroke-width="2" 
                          fill="none" />
                </svg>
                
                <div style="display:flex;align-items:stretch;position:relative;z-index:2">
                    <!-- 左侧主题 -->
                    <div ref="mainTopic" style="flex-shrink:0;padding:20px 30px;margin-right:80px;display:flex;align-items:center;justify-content:center;">
                        <v-chip
                                class="font-weight-bold"
                                color="#BBDEFB"
                                label
                                x-large
                                style="font-size:24px;height:60px;padding:0 30px;"
                        >
                            {{problem_subclass}}
                        </v-chip>
                    </div>
                    
                    <!-- 右侧子项列表 -->
                    <div style="flex-grow:1;display:flex;flex-direction:column;gap:15px;">
                        <div v-for="item in allDataInfo" :key="item.title" :ref="'category_' + item.title" style="position:relative;">
                            <div style="border: 2px dashed;border-radius:8px;padding:10px;" :style="{borderColor: item.color}">
                                <div class="d-flex align-center" style="margin-bottom:8px;">
                                    <v-chip
                                            class="font-weight-bold"
                                            :color="item.color"
                                            label
                                            style="font-size:16px;"
                                    >
                                        {{ item.title }}
                                    </v-chip>
                                </div>
                                <div v-if="item.content.length > 0">
                                    <v-hover v-for="(content,index) in item.content" :key="index">
                                        <template v-slot:default="{ hover }">
                                            <v-card :elevation="hover ? 10 : 3" style="margin:5px 0" @click="go_to_ll(content.linkInfo)">
                                                <h4 style="padding:8px">{{(index+1)}}、{{ content.data }}</h4>
                                            </v-card>
                                        </template>
                                    </v-hover>
                                </div>
                                <div v-else style="padding:5px;color:#999;font-size:14px;">暂无数据</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </v-card>
    </v-card>
</template>
<script>
    export default {
        data () {
            return {
                fish_bone_sql:"select l.id as long_id,l.measure,l.problem_process_id,process.process_type,l.reason_analyse_id,r.type,r.reason_analyse,r.if_primary,l.lessons_learn_id,ll.problem_subclass from tb_long_term_measure l left join tb_lessons_learn ll on l.lessons_learn_id = ll.id and ll.MARK_FOR_DELETE = 0 left join tb_problem_process process on l.PROBLEM_PROCESS_ID = process.id and process.MARK_FOR_DELETE = 0 left join tb_reason_analyse r on l.REASON_ANALYSE_ID = r.id and r.MARK_FOR_DELETE = 0 where l.MARK_FOR_DELETE = 0 and l.RELATION_LESSONS_LEARN = 'Y' and l.REASON_ANALYSE_ID is not null  [and ll.problem_subclass = #{problem_subclass}]",
                matrix_sql:"select ll.problem_subclass,r.type,count(1) num from tb_long_term_measure l left join tb_lessons_learn ll on l.lessons_learn_id = ll.id and ll.MARK_FOR_DELETE = 0 left join tb_reason_analyse r on l.REASON_ANALYSE_ID = r.id and r.MARK_FOR_DELETE = 0 where l.MARK_FOR_DELETE = 0 and l.RELATION_LESSONS_LEARN = 'Y' and l.REASON_ANALYSE_ID is not null and ll.problem_subclass != '其他（需要备注）' [and ll.problem_class_id = #{problem_class_id}] group by r.type,ll.problem_subclass order by r.type,ll.problem_subclass",
                problem_class_sql:"SELECT problem_class as label,id as value FROM tm_problem_class where MARK_FOR_DELETE = 0",
                problem_subclass:'',
                selectedProblemClass: 'ALL',
                problemClassList: [{value: 'ALL', label: '全部'}],
                topDataInfo:[],
                bottomDataInfo:[],
                allDataInfo:[],
                connectionLines:[],
                matrixXData:['人', '机', '料', '法', '环', '测'],
                matrixYData:[],
                matrix:[],
                matrixEvent:'',
                visualMapMax:2,
                dataZoomEnd:100,
            }
        },
        methods: {
            show(){
                app.utils.showMessage(this.prop);
            },
            go_to_ll(data){
                this.$emit('toPage', 'vbd924c209c45508ce0bc310855', {"problem_process_id":data.problem_process_id,"process_type":data.process_type,"long_id":data.long_id,"reason_analyse_id":data.reason_analyse_id});
            },
            loadProblemClassList() {
                let _this = this;
                let params = {"SQL": this.problem_class_sql};

                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: false,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params),
                    },
                    callBack(res) {
                        // 过滤掉"其他"和"设备"选项
                        let filteredRows = res.rows.filter(item =>
                            item.label !== '其他' && item.label !== '设备'
                        );

                        // 添加"全部"选项
                        let allList = [{value: 'ALL', label: '全部'}].concat(filteredRows);
                        _this.problemClassList = allList;
                    },
                });
            },
            onProblemClassChange() {
                this.loadMatrixData();
            },
            generateHeatmapData() {
                // 初始化一个二维数组，全部填充0
                const dataMap = this.matrixYData.map(() => new Array(this.matrixXData.length).fill(0));

                // 填充实际数据
                this.matrix.forEach(item => {
                    const yIndex = this.matrixYData.indexOf(item.problem_subclass);
                    const xIndex = this.matrixXData.indexOf(item.type);
                    if (yIndex !== -1 && xIndex !== -1) {
                        dataMap[yIndex][xIndex] += item.num;
                    }
                });

                // 转换为目标格式，包括所有可能的组合
                const result = [];
                for (let y = 0; y < this.matrixYData.length; y++) {
                    for (let x = 0; x < this.matrixXData.length; x++) {
                        result.push([x, y, dataMap[y][x] || '-']);
                    }
                }

                return result;
            },
            loadMatrixData(){
                let _this = this;
                let params = {"SQL": this.matrix_sql};

                // 设置查询条件
                let queryCondition = {};
                if(this.selectedProblemClass && this.selectedProblemClass !== 'ALL') {
                    queryCondition["problem_class_id"] = this.selectedProblemClass;
                }

                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: false,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params),
                        queryCondition: queryCondition
                    },
                    callBack(res) {
                        let subClass = new Set();
                        let max = 2;
                        res.rows.forEach(function (item) {
                            item.type = app.utils.getEntryValue("REASON_ANALYSE_TYPE", item.type);
                            subClass.add(item.problem_subclass);
                            if(item.num > max){
                                max = item.num;
                            }
                        })

                        _this.visualMapMax = max;

                        _this.matrix  = res.rows;

                        // 创建一个包含problem_subclass和总数的数组
                        let subClassWithTotals = [];
                        Array.from(subClass).forEach(cls => {
                            let total = 0;
                            // 计算每个类别在各个原因类型下的总数
                            res.rows.forEach(item => {
                                if (item.problem_subclass === cls) {
                                    total += Number(item.num);
                                }
                            });
                            subClassWithTotals.push({
                                name: cls,
                                total: total
                            });
                        });

                        // 按总数排序，大的在上面（索引小），小的在下面（索引大）
                        subClassWithTotals.sort((a, b) => b.total - a.total);
                        _this.matrixYData = subClassWithTotals.map(item => item.name);

                        if(_this.matrixYData.length > 5){
                            _this.dataZoomEnd = Math.ceil(500/_this.matrixYData.length)
                        }

                        _this.loadMatrixChart();
                        if(_this.matrixYData.length > 0){
                            _this.problem_subclass = _this.matrixYData[0];
                            _this.loadFishBoneData();
                        }
                    },
                })
            },
            loadMatrixChart(){
                this.matrixEvent = this.matrixEvent || this.$echarts.init(this.$refs.matrixTarget);
                const data = this.generateHeatmapData();
                let option = {
                    tooltip: {

                        trigger: 'item',
                        formatter: function(params) {
                            const data = params.data;
                            const xName = option.xAxis.data[data[0]];
                            const yName = option.yAxis.data[data[1]];
                            const value = data[2];

                            // 添加图标
                            const icon = value > 0 ? '●' : '○';

                            return `
      <div style="font-size:14px">
        <div style="font-weight:bold;margin-bottom:5px">
          ${icon} ${yName}
        </div>
        <div style="display:flex">
          <span style="width:80px;color:#888">所属分类：</span>
          <span>${xName}</span>
        </div>
        <div style="display:flex">
          <span style="width:80px;color:#888">出现次数：</span>
          <span style="color:${params.color}">
            ${value === '-' ? '无记录' : value + '次'}
          </span>
        </div>
      </div>
    `;
                        }
                    },
                    grid: {
                        left: '2%',
                        right:'2%',
                        top: '2%',
                        bottom:'3%',
                        containLabel:true
                    },
                    xAxis: {
                        type: 'category',
                        position:'top',
                        data: this.matrixXData,
                        splitArea: {
                            show: true
                        },
                        axisLabel: {
                            color: '#66BB6A',
                            fontWeight: 'bold'
                        }
                    },
                    yAxis: {
                        type: 'category',
                        data: this.matrixYData,
                        splitArea: {
                            show: true
                        },
                        inverse: true,  // 反转Y轴，确保最大值在最上面
                        axisLabel: {
                            color: '#42A5F5',
                            fontWeight: 'bold'
                        }
                    },
                    dataZoom: [
                        {
                            yAxisIndex:0,
                            left:'0.5%',
                            show: true,
                            realtime: true,
                            start: 0,
                            end: this.dataZoomEnd
                        }
                    ],
                    visualMap: {
                        show: false,
                        min: 1,
                        max: this.visualMapMax,
                        color:['#66BB6A','#66BB6A']
                    },
                    series: [
                        {
                            name: '矩阵图',
                            type: 'heatmap',
                            data: data,
                            label: {
                                show: true
                            },
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                }
                let _this = this;
                option && this.matrixEvent.setOption(option);
                this.matrixEvent.off('click');
                this.matrixEvent.on('click', function (params) {
                    _this.problem_subclass = _this.matrixYData[params.data[1]];
                    _this.loadFishBoneData();
                });
            },
            loadFishBoneData(){
                let _this = this;
                let params = {"SQL": this.fish_bone_sql};

                app.utils.ajaxRequest({
                    hideMsg: true,
                    hideMask: false,
                    url: app.path().dispose + "?functionCode=QMS_CUSTOM_QUERY_SQL",
                    params: {
                        functionParam: JSON.stringify(params),
                        "queryCondition[problem_subclass]": _this.problem_subclass,
                    },
                    callBack(res) {
                        res.rows.forEach(function (item) {
                            item.type = app.utils.getEntryValue("REASON_ANALYSE_TYPE", item.type);
                        })
                        _this.transformData(res.rows);
                    },
                })
            },
            transformData(originalData) {
                // Define all categories in order
                const allCategories = [
                    { type: '人', title: '【人】', color: '#74b567' },
                    { type: '机', title: '【机】', color: '#26C6DA' },
                    { type: '料', title: '【料】', color: '#459ce3' },
                    { type: '法', title: '【法】', color: '#f8b500' },
                    { type: '环', title: '【环】', color: '#8e81bc' },
                    { type: '测', title: '【测】', color: '#7dcdf4' }
                ];

                // Initialize the result array
                const allDataInfo = allCategories.map(cat => ({
                    title: cat.title,
                    color: cat.color,
                    content: []
                }));

                // Process each item in the original data
                originalData.forEach(item => {
                    const contentItem = {
                        linkInfo: item,
                        data: item.measure, //长期措施
                    };

                    // Find the matching category
                    const category = allCategories.find(cat => cat.type === item.type);
                    if (category) {
                        const target = allDataInfo.find(info => info.title === category.title);
                        if (target) {
                            target.content.push(contentItem);
                        }
                    }
                });

                this.allDataInfo = allDataInfo;
                
                // 等待DOM更新后计算连接线
                this.$nextTick(() => {
                    this.calculateConnectionLines();
                });
            },
            calculateConnectionLines() {
                // 清空之前的连接线
                this.connectionLines = [];
                
                // 获取主题元素
                const mainTopic = this.$refs.mainTopic;
                if (!mainTopic) return;
                
                const mainRect = mainTopic.getBoundingClientRect();
                const containerRect = this.$refs.mindmapSvg.getBoundingClientRect();
                
                // 主题右侧中心点（相对于SVG容器）
                const mainX = mainRect.right - containerRect.left;
                const mainY = mainRect.top + mainRect.height / 2 - containerRect.top;
                
                // 水平延伸的距离
                const horizontalExtend = 40;
                
                // 为每个分类创建直角连接线
                this.allDataInfo.forEach((item, index) => {
                    const categoryRef = this.$refs['category_' + item.title];
                    if (categoryRef && categoryRef.length > 0) {
                        const categoryElement = categoryRef[0];
                        const categoryRect = categoryElement.getBoundingClientRect();
                        
                        // 分类左侧中心点（相对于SVG容器）
                        const categoryX = categoryRect.left - containerRect.left;
                        const categoryY = categoryRect.top + categoryRect.height / 2 - containerRect.top;
                        
                        // 创建直角路径：从主题出发 -> 水平延伸 -> 垂直转向 -> 到达分类
                        const path = `M ${mainX} ${mainY} L ${mainX + horizontalExtend} ${mainY} L ${mainX + horizontalExtend} ${categoryY} L ${categoryX} ${categoryY}`;
                        
                        // 添加连接线
                        this.connectionLines.push({
                            path: path,
                            color: item.color
                        });
                    }
                });
            }
        },
        mounted () {
            this.loadProblemClassList();
            this.loadMatrixData();
            window.onresize=()=>{
                this.matrixEvent.resize();
                this.calculateConnectionLines();
            }
        },
        props: {
            prop:{type:String,desc:'基本参数'}
        }
    }
</script>
